/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package wat.serwerapp.main;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import wat.serverapp.remote.ClassProviderImpl;
import wat.ziszcommon.transport.MethodCallMessage;

/**
 *
 * @author Krzysztof Wilkos
 */
public class AccessControler {
    private static AccessControler instance = null;

    private AccessControler() {

    }

    public static AccessControler getInstance() {
        if(instance==null) {
            instance = new AccessControler();
        }
        return instance;
    }

    public Object processMethodCall(MethodCallMessage msg) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, InstantiationException {
        System.out.println("msg.getInterFace(): "+ msg.getInterFace());
        if(msg.getInterFace().equals("wat.ziszcommon.remote.ClassProvider")) {
            ClassProviderImpl classProvider = new ClassProviderImpl();
            for(Method m: classProvider.getClass().getMethods()) {
                if(m.getName().equals(msg.getMethod())) {
                    return m.invoke(classProvider, msg.getParams());
                }
            }
        }

        String packageName =  msg.getInterFace().substring(0, msg.getInterFace().lastIndexOf("."));
        String interfaceName = msg.getInterFace().substring(msg.getInterFace().lastIndexOf("$")+1, msg.getInterFace().length());
        String implClassName = packageName + "." + interfaceName + "Impl";
        System.out.println("Loading service implementation class " +implClassName);

        Class implClass = Class.forName(implClassName);
        System.out.println("Implementation class loaded.");
        Object implClassInstance = implClass.newInstance();
        for(Method m: implClassInstance.getClass().getMethods()) {
            if(m.getName().equals(msg.getMethod())) {
                return m.invoke(implClassInstance, msg.getParams());
            }
        }
        return null;
    }
}
